package com.vegetable.modules.oauth2;

import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class ChinaUMSQueryService {
    private String appId;
    private String accessToken;
    private boolean isProduction;

    // 构造函数
    public ChinaUMSQueryService(String appId, String accessToken, boolean isProduction) {
        this.appId = appId;
        this.accessToken = accessToken;
        this.isProduction = isProduction;
    }

    // 获取API基础URL
    private String getBaseUrl() {
        return isProduction ? "https://api-mop.chinaums.com" : "https://test-api-open.chinaums.com";
    }

    // 构建认证头
    private String buildAuthHeader() {
        return "OPEN-ACCESS-TOKEN AccessToken=\"" + accessToken + "\", AppId=\"" + appId + "\"";
    }

    // 发送POST请求通用方法
    private JSONObject sendPostRequest(String endpoint, JSONObject requestData) {
        log.info("请求的参数:{}", requestData);
        try {
            URL url = new URL(getBaseUrl() + endpoint);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Authorization", buildAuthHeader());
            connection.setDoOutput(true);

            // 发送请求数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestData.toString().getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 读取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }

                    return new JSONObject(response.toString());
                }
            } else {
                JSONObject error = new JSONObject();
                error.put("respCode", "HTTP_" + responseCode);
                error.put("respDesc", "HTTP请求失败，状态码: " + responseCode);
                return error;
            }
        } catch (Exception e) {
            JSONObject error = new JSONObject();
            error.put("respCode", "EXCEPTION");
            error.put("respDesc", "请求异常: " + e.getMessage());
            return error;
        }
    }

    /**
     * 1.1 实时交易查询
     * @param groupCode 集团号(查询类型为集团时必填)
     * @param mchntNo 商户号(查询类型为商户时必填)
     * @param queryType 查询类型(group:集团, merchant:商户)
     * @param transBeginTime 交易开始时间(格式: 2019/9/10 11:39)
     * @param transEndTime 交易结束时间(格式: 2019/9/10 11:39)
     * @param termNo 终端号(可选)
     * @param mchntOrderId 商户订单号(可选)
     * @param refNo 检索参考号(可选)
     * @param pageIdx 当前页码
     * @param pageSize 每页数量
     * @param belongBranch 商户机构代码
     * @return 查询结果JSON对象
     */
    public JSONObject queryRealTimeTransaction(
            String groupCode, String mchntNo, String queryType,
            String transBeginTime, String transEndTime, String termNo,
            String mchntOrderId, String refNo, int pageIdx, int pageSize,
            String belongBranch) {

        JSONObject requestData = new JSONObject();
        if (groupCode != null) requestData.put("groupCode", groupCode);
        if (mchntNo != null) requestData.put("mchntNo", mchntNo);
        requestData.put("queryType", queryType);
        requestData.put("appId", appId);
        requestData.put("transBeginTime", transBeginTime);
        requestData.put("transEndTime", transEndTime);
        if (termNo != null) requestData.put("termNo", termNo);
        if (mchntOrderId != null) requestData.put("mchntOrderId", mchntOrderId);
        if (refNo != null) requestData.put("refNo", refNo);
        requestData.put("pageIdx", pageIdx);
        requestData.put("pageSize", pageSize);
        requestData.put("belongBranch", belongBranch);

        return sendPostRequest("/v1/uis/wf/query-trans", requestData);
    }

    /**
     * 1.2 对账明细查询
     * @param beginSettDate 开始清算日期(格式: YYYYMMDD)
     * @param endSettDate 结束清算日期(格式: YYYYMMDD)
     * @param beginTransDate 开始交易日期(格式: YYYY-MM-DD hh24:mi:ss, 可选)
     * @param endTransDate 结束交易日期(格式: YYYY-MM-DD hh24:mi:ss, 可选)
     * @param mchntNo 商户编号
     * @param busiType 多应用编号
     * @param transChnl 交易渠道(可选)
     * @param termNo 终端号(可选)
     * @param refId 交易参考号(可选)
     * @param mchntOrderId 商户订单号(可选)
     * @param umsOrderId 银商订单号(可选)
     * @param pageIdx 当前页码
     * @param pageSize 每页数量
     * @param groupCode 集团编号(可选)
     * @param queryType 查询类型(merchant/group)
     * @return 查询结果JSON对象
     */
    public JSONObject querySettlementDetail(
            String beginSettDate, String endSettDate, String beginTransDate,
            String endTransDate, String mchntNo, String busiType, String transChnl,
            String termNo, String refId, String mchntOrderId, String umsOrderId,
            int pageIdx, int pageSize, String groupCode, String queryType) {

        JSONObject requestData = new JSONObject();
        requestData.put("beginSettDate", beginSettDate);
        requestData.put("endSettDate", endSettDate);
        if (beginTransDate != null) requestData.put("beginTransDate", beginTransDate);
        if (endTransDate != null) requestData.put("endTransDate", endTransDate);
        requestData.put("mchntNo", mchntNo);
        requestData.put("busiType", busiType);
        if (transChnl != null) requestData.put("transChnl", transChnl);
        if (termNo != null) requestData.put("termNo", termNo);
        if (refId != null) requestData.put("refId", refId);
        if (mchntOrderId != null) requestData.put("mchntOrderId", mchntOrderId);
        if (umsOrderId != null) requestData.put("umsOrderId", umsOrderId);
        requestData.put("pageIdx", pageIdx);
        requestData.put("pageSize", pageSize);
        if (groupCode != null) requestData.put("groupCode", groupCode);
        requestData.put("queryType", queryType);

        return sendPostRequest("/v1/uis/wf/query-settle-detail", requestData);
    }

    /**
     * 1.3 实时交易汇总查询
     * @param transBeginTime 开始交易时间(格式: YYYY-MM-DD hh24:mi:ss)
     * @param transEndTime 结束交易时间(格式: YYYY-MM-DD hh24:mi:ss)
     * @param mchntNo 商户编号(可选)
     * @param groupCode 集团编号(可选)
     * @param queryType 查询类型(merchant/group)
     * @param belongBranch 所属分支机构代码
     * @return 查询结果JSON对象
     */
    public JSONObject queryTransactionSummary(
            String transBeginTime, String transEndTime, String mchntNo,
            String groupCode, String queryType, String belongBranch) {

        JSONObject requestData = new JSONObject();
        requestData.put("transBeginTime", transBeginTime);
        requestData.put("transEndTime", transEndTime);
        if (mchntNo != null) requestData.put("mchntNo", mchntNo);
        if (groupCode != null) requestData.put("groupCode", groupCode);
        requestData.put("queryType", queryType);
        requestData.put("belongBranch", belongBranch);

        return sendPostRequest("/v1/uis/wf/query-trans-summary", requestData);
    }

    /**
     * 1.4 对账汇总查询
     * @param beginDate 开始交易时间(格式: YYYYMMDD)
     * @param endDate 结束交易时间(格式: YYYYMMDD)
     * @param mchntNo 商户编号
     * @param belongBranch 所属分支机构代码
     * @return 查询结果JSON对象
     */
    public JSONObject queryAccountSummary(
            String beginDate, String endDate, String mchntNo, String belongBranch) {

        JSONObject requestData = new JSONObject();
        requestData.put("beginDate", beginDate);
        requestData.put("endDate", endDate);
        requestData.put("mchntNo", mchntNo);
        requestData.put("belongBranch", belongBranch);

        return sendPostRequest("/v1/uis/wf/account-summary", requestData);
    }

    // 使用示例
    public static void main(String[] args) {
        // 您的认证信息
        String appId = "10037e6f68e462980169043abe98002a";
        String accessToken = "49d2cc4abbf742a2a458a7404f2ffd86"; // 这里需要替换为实际获取的AccessToken
        boolean isProduction = false; // 使用测试环境

        // 创建查询服务对象
        ChinaUMSQueryService queryService = new ChinaUMSQueryService(appId, accessToken, isProduction);

        // 示例1: 实时交易查询
        JSONObject realTimeResult = queryService.queryRealTimeTransaction(
                null, // groupCode (查询类型为商户时不需填写)
                "商户号", // mchntNo
                "merchant", // queryType
                "2023/01/01 00:00", // transBeginTime
                "2023/01/01 23:59", // transEndTime
                null, // termNo
                null, // mchntOrderId
                null, // refNo
                1, // pageIdx
                10, // pageSize
                "机构代码" // belongBranch
        );

        log.info("实时交易查询结果:");
        log.info(realTimeResult.toString(2));

        // 示例2: 对账明细查询
        JSONObject settleDetailResult = queryService.querySettlementDetail(
                "20230101", // beginSettDate
                "20230103", // endSettDate
                null, // beginTransDate
                null, // endTransDate
                "商户号", // mchntNo
                "应用编号", // busiType
                null, // transChnl
                null, // termNo
                null, // refId
                null, // mchntOrderId
                null, // umsOrderId
                1, // pageIdx
                10, // pageSize
                null, // groupCode
                "merchant" // queryType
        );

        log.info("对账明细查询结果:");
        log.info(settleDetailResult.toString(2));

        // 示例3: 实时交易汇总查询
        JSONObject transSummaryResult = queryService.queryTransactionSummary(
                "2023-01-01 00:00:00", // transBeginTime
                "2023-01-01 23:59:59", // transEndTime
                "商户号", // mchntNo
                null, // groupCode
                "merchant", // queryType
                "机构代码" // belongBranch
        );

        log.info("实时交易汇总查询结果:");
        log.info(transSummaryResult.toString(2));

        // 示例4: 对账汇总查询
        JSONObject accountSummaryResult = queryService.queryAccountSummary(
                "20230101", // beginDate
                "20230103", // endDate
                "商户号", // mchntNo
                "机构代码" // belongBranch
        );

        log.info("对账汇总查询结果:");
        log.info(accountSummaryResult.toString(2));
    }
}
